package com.bayair.doctor.net;

import android.util.Log;

import com.bayair.doctor.net.config.HttpConfig;
import com.bayair.doctor.net.exception.ServerException;
import com.blankj.utilcode.util.NetworkUtils;
import java.nio.charset.Charset;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * 拦截器管理
 */
public class InterceptorUtil {

    public static String TAG = "InterceptorUtil";

    private static final String HEADER_CONTENT_TYPE = "Content-Type";
    private static final String HEADER_APPLICATION_JSON = "application/json";

    private static final String HEADER_ACCEPT = "Accept";
    private static final String HEADER_AUTHORIZATION = "Authorization";
    private static final Charset UTF8 = Charset.forName("UTF-8");

    //添加日志拦截器
    public static HttpLoggingInterceptor LogInterceptor() {
        return new HttpLoggingInterceptor(s -> {
            if (HttpConfig.DEBUG) {
                Log.e(TAG, "log: " + s);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别
    }

    //网络监听拦截器
    public static Interceptor NetworkInterceptor() {
        return  chain -> {
            if (NetworkUtils.isConnected()) {
                return chain.proceed(chain.request());
            } else {
                throw new ServerException(ServerException.CUSTOM_ERROR.NET_ERROR);
            }
        };
    }


    //添加header
    public static Interceptor HeaderInterceptor() {
        return  chain -> {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();
            builder.header(HEADER_CONTENT_TYPE, HEADER_APPLICATION_JSON);
            Response response = chain.proceed(builder.build());
            return response;
        };
    }

    //requestBody添加公共参数
    public static Interceptor ParamInterceptor() {

        return chain -> {
            Request oldRequest = chain.request();
            Request newRequest = HttpUtils.updateRequestBody(oldRequest, RxParams.getCommonParams());
            return chain.proceed(newRequest);
        };
    }
}


